class EventEmitter {
    events = {
        /**
         * connect: Set,
         * close: Set,
         * portChange: Set
         */
    }
    // 注册
    on(eventName, handler) {
        if( !this.events[eventName]) {
            this.events[eventName] = new Set()
        }
        this.events[eventName].add(handler)
    }

    once(eventName, handler) {
        handler.once = true
        this.on(eventName, handler)
    }

    emit(eventName, ...args) {
        if( !this.events[eventName]) {
            return
        }
        for( let handler of this.events[eventName].keys()) {
            handler.apply(this, args)
            if( handler.once) {
                this._removeHandler(eventName, handler)
            }
        }
    }

    removeListeners(eventName, handler) {
        if( !this.events[eventName]) {
            return
        }
        this._removeHandler(eventName, handler)
    }

    removeAllListeners(eventName, handler) {
        if( !this.events[eventName]) {
            return
        }
        delete this.events[eventName]
    }

    _removeHandler(eventName, handler) {
        this.events[eventName].delete(handler)
    }
}

module.exports = {
    EventEmitter
}
